package com.dolawing.phonecallapp.blacknumber.function;

import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.SmsMessage;
import android.util.Log;

import com.dolawing.phonecallapp.blacknumber.db.BlackNumberDao;

/**
 * 短信接收者
 *
 */
public class SmsRecevier extends BroadcastReceiver {

    private SharedPreferences sp;
    private DevicePolicyManager devicePolicyManager;
    private BlackNumberDao blackNumberDao;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        Log.i("i", "已经拦截到了短信");
        sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        blackNumberDao = new BlackNumberDao(context);
        //判断保护是否开启
        boolean isprotected = sp.getBoolean("isprotected", false);
        if(isprotected){
            devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for(Object pdu:pdus){
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
                String address = smsMessage.getDisplayOriginatingAddress();

                //判断是不是黑名单的一个短信
                boolean isBlackNumber = blackNumberDao.isBlackNumber(address);
                if(isBlackNumber){
                    abortBroadcast();
                }
            }
        }
    }

}
